package com.share.constant.controller;

import cn.hutool.core.io.FileUtil;

import com.share.constant.Result;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;


@RestController
@RequestMapping("/File")
@Slf4j
public class ImageController {
    /*
    * 这一部分可以做文件分类的预览，目前只是支持图片，但返回的都是二进制数据，前端应该有对应的工具预览不同类型文件
    * */
    String ROOT_PATH="e:\\A";//文件保存地址
    private static final Logger logger = LoggerFactory.getLogger(ImageController.class);
    @PostMapping("/upload") //文件上传访问路径
    public Result upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();//aaa.png
        String mainName = FileUtil.mainName(originalFilename);//aaa
        String extName = FileUtil.extName(originalFilename);//png
        if (!FileUtil.exist(ROOT_PATH)){
            FileUtil.mkdir(ROOT_PATH);
        }
        if (FileUtil.exist(ROOT_PATH+File.separator+originalFilename)){
            originalFilename=System.currentTimeMillis()+"_"+mainName+"."+extName;
        }
        File saveFile=new File(ROOT_PATH+File.separator+originalFilename);
        try {
            file.transferTo(saveFile);//把文件存储到本地磁盘
        } catch (Exception e) {
            log.error("文件上传失败{}",e.getClass());
            return Result.fail(500,"文件上传失败");
        }
        String url = "http://localhost:8080/File/download/"+originalFilename;
        return  Result.ok(url);//前端拿到下载的url
    }
    @GetMapping("/download/{fileName}")
    public  void  download(@PathVariable String fileName, HttpServletResponse httpServletResponse) throws IOException {
        String  filePath = ROOT_PATH+File.separator+ fileName;
        logger.info("下载文件："+filePath);
        if (!FileUtil.exist(filePath)){
            return;
        }
        //以二进制流返回文件
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }
}
